package com.ocp.socket.server.service;

import com.alibaba.fastjson.JSON;
import com.ocp.socket.busi.dataAripUtils.mapper.DataAirpUtilsMapper;
import com.ocp.socket.busi.dataMilkListUtils.bean.DataMilkListVo;
import com.ocp.socket.busi.dataMilkListUtils.mapper.DataMilkListUtilsMapper;
import com.ocp.socket.busi.dataMilkUtils.bean.CleanDetails;
import com.ocp.socket.busi.dataMilkUtils.bean.DataMilkVo;
import com.ocp.socket.busi.dataMilkUtils.bean.QueryDataMilkVo;
import com.ocp.socket.busi.dataMilkUtils.mapper.DataMilkUtilsMapper;
import com.ocp.socket.busi.dataTempUtils.mapper.DataTempUtilsMapper;
import com.ocp.socket.busi.lineInfo.mapper.BaseLineInfoMapper;
import com.ocp.socket.busi.utils.mapper.UtilsMapper;
import com.ocp.socket.busi.utils.service.IDataUtilService;
import com.ocp.socket.busi.warnItem.bean.BaseWarnItem;
import com.ocp.socket.busi.warnItem.mapper.BaseWarnItemMapper;
import com.ocp.socket.busi.warnMsg.bean.BaseWarnMsg;
import com.ocp.socket.busi.warnMsg.mapper.BaseWarnMsgMapper;
import com.ocp.socket.common.Constants;
import com.ocp.socket.common.bean.DevInfo;
import com.ocp.socket.common.enums.CacheKeyEnum;
import com.ocp.socket.common.enums.DeviceWarnEnum;
import com.ocp.socket.common.enums.MsgTypeEnum;
import com.ocp.socket.common.enums.WarnCodeEnum;
import com.ocp.socket.common.utils.CommonUtils;
import com.ocp.socket.common.utils.RedisUtil;
import com.ocp.socket.common.utils.SessionUtil;
import com.ocp.socket.common.utils.TableUtils;
import com.ocp.socket.server.vo.DataVo;
import com.ocp.socket.server.vo.MessageVo;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: zhangzh
 * @Date: 2019/3/4 10:08
 * @Description: 挤奶 清洗 辅助设备的报文解析
 * @Version: 1.0.0
 */
@Service("milkService")
@Transactional
public class MilkService {
    private static final Logger logger = LoggerFactory.getLogger(MilkService.class);

    @Value("${msgDataDb}")
    private String msgDataDb;

    @Value("${airpMsg}")
    private String airp;

    @Value("${milkMsg}")
    private String milk;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    DataMilkUtilsMapper dataMilkUtilsMapper;

    @Autowired
    DataMilkListUtilsMapper dataMilkListUtilsMapper;

    @Autowired
    BaseWarnMsgMapper baseWarnMsgMapper;

    @Autowired
    BaseWarnItemMapper baseWarnItemMapper;

    @Autowired
    DataTempUtilsMapper dataTempUtilsMapper;

    @Autowired
    DataAirpUtilsMapper dataAirpUtilsMapper;

    @Autowired
    BaseLineInfoMapper baseLineInfoMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IDataUtilService dataUtilService;


    /**
     * 处理挤奶 清洗 辅助设备的报文
     *
     * @param messageVo
     * @return
     */
    public MessageVo saveMilkData(MessageVo messageVo, IoSession session) throws ParseException {
        if (messageVo.getDataVoMap().size() < 1) {
            logger.info("当前挤奶清洗或者辅助设备没有配置线路！");
            messageVo.setReturnCode("1");
            messageVo.setReturnMsg("当前挤奶清洗或者辅助设备没有配置线路！");
            return messageVo;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        //获取设备信息
        DevInfo devInfo = (DevInfo) session.getAttribute(Constants.ATTRIBUTE_KEY_AUTH);
        Integer orgId = devInfo.getOrgId();
        String valvL01Key = CacheKeyEnum.DEVICE_VALV_L01.getCacheKey()+devInfo.getHallId();
        String valvL02Key = CacheKeyEnum.DEVICE_VALV_L02.getCacheKey()+devInfo.getHallId();
        String valvFlagKey = CacheKeyEnum.DEVICE_VALV_FLAG.getCacheKey()+devInfo.getHallId();
        Integer valvL01KeyCnt = redisUtil.get(valvL01Key, Integer.class);
        if (valvL01KeyCnt == null) {
            valvL01KeyCnt = 0;
        }
        logger.debug("valvL01KeyCnt:{}", valvL01KeyCnt);
        Integer valvL02KeyCnt = redisUtil.get(valvL02Key, Integer.class);
        if (valvL02KeyCnt == null) {
            valvL02KeyCnt = 0;
        }
        logger.debug("valvL02KeyCnt:{}", valvL02KeyCnt);
        Integer valvFlag = redisUtil.get(valvFlagKey, Integer.class);
        if (valvFlag == null) {
            valvFlag = 0;
        }
        //获取业务类型
        String type = devInfo.getTypeCode().toLowerCase();
        logger.debug("valvFlag:{}", valvFlag);
        if ("airp".equals(type) || "temp".equals(type)) {
            logger.debug("设备SN的类型与硬件信号类型不匹配，信号忽略！");
            messageVo.setReturnCode("1");
            messageVo.setReturnMsg("设备SN的类型与硬件信号类型不匹配，信号忽略！");
            return messageVo;
        }
        //当前挤奶清洗记录表
        String nowMilkTableName = TableUtils.getDataTableName(msgDataDb, type, orgId, messageVo.getDataTime().substring(0, 8));
        //当前挤奶清洗记录表
        String nowMilkListTableName = TableUtils.getRunListTableName(msgDataDb, type);
        //需要闭环的表名
        String runStartMilkListTableName = null;
        //挤奶清洗状态表
        String milkStatTableName = TableUtils.getDataStatTableName(type, orgId);
        //创建温度记录表
        dataUtilService.createDataTableIfNotExist(nowMilkTableName, milk);
        //创建当前温度表
        dataUtilService.createStatTableIfNotExist(milkStatTableName, milk);
        //创建MILK的时间拉链表
        dataUtilService.createRunListTableIfNotExist(nowMilkListTableName, milk);
        //拉链表的最新条记录
        Map<String, DataMilkListVo> dataMilkListMap = new HashMap<String, DataMilkListVo>();
        //报警信息MAP
        Map<String, String> baseWarnMsgMap = new HashMap<String, String>();
        //报警信息稳定时长MAP
        Map<String, Integer> baseWarnMsgTimesMap = new HashMap<String, Integer>();
        //报警项信息MAP
        Map<String, BaseWarnItem> baseWarnItemMap = new HashMap<String, BaseWarnItem>();
        //挤奶信号对应的数据map
        Map<String, DataMilkVo> dataMilkMap = new HashMap<String, DataMilkVo>();
        //根据奶厅查询当前奶厅挤奶清洗的状态
        DataMilkVo dataMilkVo = null;
        QueryDataMilkVo queryDataMilkVo = new QueryDataMilkVo();
        queryDataMilkVo.setHallId(devInfo.getHallId());
        List<DataMilkVo> dataMilkList = dataMilkUtilsMapper.getListByTableName(milkStatTableName, queryDataMilkVo);
        for (DataMilkVo _dataMilkVo : dataMilkList) {
            if ("-1".equals(_dataMilkVo.getVal()) && dataMilkVo == null) {
                dataMilkVo = _dataMilkVo;
            }
            dataMilkMap.put(_dataMilkVo.getLineCode(), _dataMilkVo);
            if (runStartMilkListTableName == null) {
                runStartMilkListTableName = TableUtils.getRunListTableName(msgDataDb, type);
            }
        }
        dataMilkList.clear();
        //变量
        DataMilkVo _dataMilkVo = null;
        //旧数据
        if (!messageVo.isNewDataFlag()) {
            logger.debug("旧数据:{}, 数据日期:{}", messageVo.getSn(),messageVo.getDataTime());
            Map<String, DataVo> dataVoMap = messageVo.getDataVoMap();
            DataVo dataVo;
            List<DataMilkVo> datas = new ArrayList<>();
            for (String key : dataVoMap.keySet()) {
                dataVo = dataVoMap.get(key);
                _dataMilkVo = new DataMilkVo();
                _dataMilkVo.setHallId(devInfo.getHallId());
                _dataMilkVo.setTypeCode(devInfo.getTypeCode());
                _dataMilkVo.setDataTime(messageVo.getDataTime());
                _dataMilkVo.setLineCode(key);
                _dataMilkVo.setVal(dataVo.getVal());
                if ("-1".equals(dataVo.getVal())) {
                    _dataMilkVo.setRunStat("1");
                    _dataMilkVo.setRunStatDesc("运行中");
                    _dataMilkVo.setRunStatDescEn("Running");
                } else {
                    _dataMilkVo.setRunStat("0");
                    _dataMilkVo.setRunStatDesc("停止中");
                    _dataMilkVo.setRunStatDescEn("Stopping");
                }
                _dataMilkVo.setSnNo(messageVo.getSn());
                _dataMilkVo.setRunStartTime(messageVo.getDataTime());
                _dataMilkVo.setRunTimesStartTime(messageVo.getDataTime());
                _dataMilkVo.setRunTimes(0);
                datas.add(_dataMilkVo);
            }
            try {
                dataMilkUtilsMapper.insertDataMilks(nowMilkTableName, datas);
            } catch (Exception e) {
                logger.error("批量插入milk数据报错:{}", e.getMessage());
            }
            return messageVo;
        }
        //奶厅下已有且未结束的报警信息
        List<BaseWarnMsg> baseWarnMsgList = baseWarnMsgMapper.getBaseWarnMsgListByMilkHallId(devInfo.getHallId());
        for (BaseWarnMsg baseWarnMsg : baseWarnMsgList) {
            baseWarnMsgMap.put(baseWarnMsg.getWarnCode(), baseWarnMsg.getId());
            baseWarnMsgTimesMap.put(baseWarnMsg.getWarnCode(), baseWarnMsg.getEndTimes());
        }
        baseWarnMsgList.clear();

        //奶厅下最新的拉链记录
        if (runStartMilkListTableName != null) {
            List<DataMilkListVo> dataMilkListVoList = dataMilkListUtilsMapper.getInfoByTableName(runStartMilkListTableName, devInfo.getHallId());
            for (DataMilkListVo dataMilkListVo : dataMilkListVoList) {
                dataMilkListMap.put(dataMilkListVo.getLineCode(), dataMilkListVo);
            }
            dataMilkListVoList.clear();
        }

        //根据奶厅查询已配置的报警信息项
        List<BaseWarnItem> baseWarnItemList = baseWarnItemMapper.getBaseWarnItemListByMilkHallId(devInfo.getHallId());
        for (BaseWarnItem baseWarnItem : baseWarnItemList) {
            baseWarnItemMap.put(baseWarnItem.getWarnCode(), baseWarnItem);
        }
        baseWarnItemList.clear();

        if ("MILK".equals(devInfo.getTypeCode())) { //挤奶清洗

            /****
             *W037 2挤奶清洗信号异常
             * 2条信号
             * 报警关键因素 L02
             */
            if ("-1".equals(messageVo.getDataVoMap().get("L01").getVal()) && "-1".equals(messageVo.getDataVoMap().get("L02").getVal())) {
                if (baseWarnItemMap.get(WarnCodeEnum.W037.getWarnCode()) != null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W037.getWarnCode()).getIgnoreTimes()) {
                    if (baseWarnMsgMap.get(WarnCodeEnum.W037.getWarnCode()) == null) {
                        CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W037.getWarnCode(), baseWarnItemMap, messageVo, devInfo, devInfo.getSnNo(), null, redisUtil,DeviceWarnEnum.MILK.getDeviceCode());
                    } else {
                        baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W037.getWarnCode()));
                    }
                }
                return messageVo;
            } else {
                if (baseWarnMsgMap.get(WarnCodeEnum.W037.getWarnCode()) != null) {
                    if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W037.getWarnCode()) > 10) {
                        CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W037.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                    } else {
                        baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W037.getWarnCode()));
                    }
                }
            }

            StringBuffer coolTablePrefix = new StringBuffer();
            coolTablePrefix.append("data_");
            coolTablePrefix.append(MsgTypeEnum.COOL.getTypeCode().toLowerCase());
            coolTablePrefix.append("_stat");
            coolTablePrefix.append("_");
            coolTablePrefix.append(devInfo.getOrgId());
            //若为挤奶清洗转换信号，则清理之前的报警信息
            if (dataMilkVo != null && !dataMilkVo.getVal().equals(messageVo.getDataVoMap().get(dataMilkVo.getLineCode()).getVal())) {
                baseWarnMsgMapper.updateBaseWarnMsgEndTimeByHallId(devInfo.getHallId(), messageVo.getDataTime());
            }

            if(dataMilkVo == null){
                logger.debug("dataMilkVo 为空");
            }else{
                logger.debug("当前挤奶设备:"+dataMilkVo.getLineCode());
                logger.debug("当前挤奶信号:"+messageVo.getDataVoMap().get("L02").getVal());
            }
            //第一次清洗
            if(((dataMilkVo!=null && !"L02".equals(dataMilkVo.getLineCode())) || dataMilkVo == null) && "-1".equals(messageVo.getDataVoMap().get("L02").getVal())){
                logger.debug("第一次清洗");
                if(valvL01KeyCnt> 2 && valvL02KeyCnt > 2 &&  valvL01KeyCnt <=  valvL02KeyCnt*3){
                    logger.debug("当前：预冲洗");
                    redisUtil.set(valvFlagKey,1);
                }else if(valvL01KeyCnt> 2 && (valvL02KeyCnt < 2 || valvL01KeyCnt > valvL02KeyCnt*3)){
                    logger.debug("当前：循环洗");
                    redisUtil.set(valvFlagKey,2);
                }else{
                    logger.debug("非 预冲洗与循环洗 ");
                }
            }

            //清洗结束
            if (dataMilkVo != null && "L02".equals(dataMilkVo.getLineCode()) && messageVo.getDataVoMap().get("L02") != null && "-0".equals(messageVo.getDataVoMap().get("L02").getVal())) {
                logger.debug(" 清洗结束数据日期:{}", messageVo.getDataTime());
                //根据奶厅和时间查询热水和冷水的开关情况
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(sdf.parse(dataMilkVo.getRunStartTime()));
                calendar.add(Calendar.MINUTE, -30);
                //热冷水信号
//                StringBuffer valvTablePrefix = new StringBuffer();
//                valvTablePrefix.append("data_");
//                valvTablePrefix.append(MsgTypeEnum.VALV.getTypeCode().toLowerCase());
//                valvTablePrefix.append("_info_");
//                valvTablePrefix.append(devInfo.getOrgId());
//                valvTablePrefix.append("_");
//                List<String> valvTableList = utilsMapper.getTableNameList(valvTablePrefix.toString(), sdf.format(calendar.getTime()).substring(0, 8), dataMilkVo.getRunStartTime().substring(0, 8), msgDataDb);
//                int valvCnt = 0;
//                logger.info("冷热水信号判断时间:"+sdf.format(calendar.getTime())+"-"+dataMilkVo.getRunStartTime());
//                if (valvTableList.size() > 0) {
//                    valvCnt = dataMilkUtilsMapper.getMilkStatByTime(valvTableList, devInfo.getHallId(), sdf.format(calendar.getTime()), dataMilkVo.getRunStartTime());
//                }
//                logger.info("冷热水信号个数:"+valvTableList.size());
                //挤奶清洗信号
                StringBuffer milkTablePrefix = new StringBuffer();
                milkTablePrefix.append("data_");
                milkTablePrefix.append(MsgTypeEnum.MILK.getTypeCode().toLowerCase());
                milkTablePrefix.append("_info_");
                milkTablePrefix.append(devInfo.getOrgId());
                milkTablePrefix.append("_");
//                List<String> milkTableList = utilsMapper.getTableNameList(milkTablePrefix.toString(), sdf.format(calendar.getTime()), dataMilkVo.getRunStartTime(), msgDataDb);
//                //挤奶信号在时间段内是否运行过
//                String milkIsRunByTime = null;
//                if (milkTableList.size() > 0) {
//                    milkIsRunByTime = dataMilkUtilsMapper.getMilkIsRunByTime(milkTableList, devInfo.getHallId(), sdf.format(calendar.getTime()), dataMilkVo.getRunStartTime(), "L01");
//                }
//                milkTableList.clear();
                //温度前缀
                StringBuffer tempTablePrefix = new StringBuffer();
                tempTablePrefix.append("data_");
                tempTablePrefix.append(MsgTypeEnum.TEMP.getTypeCode().toLowerCase());
                tempTablePrefix.append("_info_");
                tempTablePrefix.append(devInfo.getOrgId());
                tempTablePrefix.append("_");
                List<String> tempTableList = utilsMapper.getTableNameList(tempTablePrefix.toString(), sdf.format(calendar.getTime()).substring(0, 8), dataMilkVo.getRunStartTime().substring(0, 8), msgDataDb);
                //气压前缀
                StringBuffer airpTablePrefix = new StringBuffer();
                airpTablePrefix.append("data_");
                airpTablePrefix.append(MsgTypeEnum.AIRP.getTypeCode().toLowerCase());
                airpTablePrefix.append("_info_");
                airpTablePrefix.append(devInfo.getOrgId());
                airpTablePrefix.append("_");
                List<String> airpTableList = utilsMapper.getTableNameList(airpTablePrefix.toString(), sdf.format(calendar.getTime()).substring(0, 8), dataMilkVo.getRunStartTime().substring(0, 8), msgDataDb);

                /****
                 * W005 预冲洗排水温度低
                 * 检测冷水和热水信号同时发出 半小时，清洗信号发出后开始记录温度T12，当清洗信号结束后，统计温度最高值，小于３８摄氏度
                 * 报警关键因素 T12
                 */

//                boolean valvL01Flag = (redisUtil.get(valvL01Key) != null && redisUtil.get(valvL01Key,Integer.class)>1) ?true:false;
//                boolean valvL02Flag = (redisUtil.get(valvL02Key) != null && redisUtil.get(valvL02Key,Integer.class)>1) ?true:false;
//                boolean valvAllFlag = valvL01Flag && valvL02Flag;
                //logger.debug("清洗运行时长:{}， 报警忽略时长:{}",dataMilkVo.getRunTimes(),baseWarnItemMap.get(WarnCodeEnum.W005.getWarnCode()).getIgnoreTimes());
                if (valvFlag == 1 && baseWarnItemMap.get(WarnCodeEnum.W005.getWarnCode()) != null && dataMilkVo!=null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W005.getWarnCode()).getIgnoreTimes()) {
                    Double _val = null;
                    if (tempTableList.size() > 0) {
                        _val = dataTempUtilsMapper.getMaxValByLineCode(tempTableList, "L12", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                    }
                    logger.debug("T12的温度:"+_val );
                    //&& "-0".equals(milkIsRunByTime)
                    if (_val != null) {
                        logger.debug("报警配置的最小温度:{}", baseWarnItemMap.get(WarnCodeEnum.W005.getWarnCode()).getMinVal() );
                        if (_val < baseWarnItemMap.get(WarnCodeEnum.W005.getWarnCode()).getMinVal()) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W005.getWarnCode()) == null) {
                                messageVo.setEndTime(true);
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W005.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L12", redisUtil,DeviceWarnEnum.TEMP.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W005.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W005.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W005.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W005.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W005.getWarnCode()));
                                }
                            }
                        }
                    }
                }
                /****
                 * W006 清洗剂循环清洗排水温度低
                 * 检测只有热水信号发出 半小时，清洗信号发出后开始记录温度T12，当清洗信号结束后，统计温度最高值，小于50摄氏度
                 * 报警关键因素 T12
                 */
                if (valvFlag == 2 && baseWarnItemMap.get(WarnCodeEnum.W006.getWarnCode()) != null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W006.getWarnCode()).getIgnoreTimes()) {
                    Double _val = null;
                    if (tempTableList.size() > 0) {
                        _val = dataTempUtilsMapper.getMaxValByLineCode(tempTableList, "L12", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                    }
                    //挤奶 并且超过20分钟 && "-0".equals(milkIsRunByTime)
                    if (_val != null) {
                        if (_val < baseWarnItemMap.get(WarnCodeEnum.W006.getWarnCode()).getMinVal()) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W006.getWarnCode()) == null) {
                                messageVo.setEndTime(true);
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W006.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L12", redisUtil,DeviceWarnEnum.TEMP.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W006.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W006.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W006.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W006.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W006.getWarnCode()));
                                }
                            }
                        }
                    }
                }
                /****
                 * W007 预冲洗水温低
                 * 检测冷水和热水信号同时发出，清洗信号发出后开始记录温度T1，当清洗信号结束后，统计温度最高值，小于45摄氏度
                 * 报警关键因素 T1
                 */
                if ((valvFlag==1) && baseWarnItemMap.get(WarnCodeEnum.W007.getWarnCode()) != null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W007.getWarnCode()).getIgnoreTimes()) {
                    Double _val = null;
                    if (tempTableList.size() > 0) {
                        _val = dataTempUtilsMapper.getMaxValByLineCode(tempTableList, "L01", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                    }
                    //挤奶 并且超过20分钟 && "-0".equals(milkIsRunByTime)
                    if (_val != null) {
                        if (_val < baseWarnItemMap.get(WarnCodeEnum.W007.getWarnCode()).getMinVal()) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W007.getWarnCode()) == null) {
                                messageVo.setEndTime(true);
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W007.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L01", redisUtil,DeviceWarnEnum.TEMP.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W007.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W007.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W007.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W007.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W007.getWarnCode()));
                                }
                            }
                        }
                    }
                }
                /****
                 * W008 预冲洗水温高
                 * 检测冷水和热水信号同时发出，清洗信号发出后开始记录温度T1，当清洗信号结束后，统计温度最高值，大于50摄氏度
                 * 报警关键因素 T1
                 */
                if (valvFlag==1 && baseWarnItemMap.get(WarnCodeEnum.W008.getWarnCode()) != null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W008.getWarnCode()).getIgnoreTimes()) {
                    Double _val = null;
                    if (tempTableList.size() > 0) {
                        _val = dataTempUtilsMapper.getMaxValByLineCode(tempTableList, "L01", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                    }
                    //挤奶 并且超过20分钟 && "-0".equals(milkIsRunByTime)
                    if (_val != null ) {
                        if (_val > baseWarnItemMap.get(WarnCodeEnum.W008.getWarnCode()).getMaxVal()) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W008.getWarnCode()) == null) {
                                messageVo.setEndTime(true);
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W008.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L01", redisUtil,DeviceWarnEnum.TEMP.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W008.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W008.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W008.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W008.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W008.getWarnCode()));
                                }
                            }
                        }
                    }
                }

                /****
                 * W009 清洗剂循环清洗水温低
                 * 清洗时，检测热水信号发出，清洗信号发出后开始记录温度T1，当清洗信号结束后，统计温度最高值，小于75摄氏度。不足1分钟，无需报警
                 * 报警关键因素 T1
                 */
                if (valvFlag == 2 && baseWarnItemMap.get(WarnCodeEnum.W009.getWarnCode()) != null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W009.getWarnCode()).getIgnoreTimes()) {
                    Double _val = null;
                    if (tempTableList.size() > 0) {
                        _val = dataTempUtilsMapper.getMaxValByLineCode(tempTableList, "L01", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                    }
                    //挤奶 并且超过20分钟 && "-0".equals(milkIsRunByTime)
                    if (_val != null) {
                        if (_val < baseWarnItemMap.get(WarnCodeEnum.W009.getWarnCode()).getMinVal()) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W009.getWarnCode()) == null) {
                                messageVo.setEndTime(true);
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W009.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L01", redisUtil,DeviceWarnEnum.TEMP.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W009.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W009.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W009.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W009.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W009.getWarnCode()));
                                }
                            }
                        }
                    }
                }

                /****
                 * W010 清洗时可能未关闭预冷冷排
                 * 清洗时：有清洗信号时，1分钟后记录T1和T2之差，当真清洗信号结束时，计算温度之差的平均值，大于5摄氏度。（有清洗信号时，前两个温度值不在技术统计范围之内）。如未配备T2，则，使用T1和T3计算
                 * 报警关键因素 T1
                 */
                if (baseWarnItemMap.get(WarnCodeEnum.W010.getWarnCode()) != null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W010.getWarnCode()).getIgnoreTimes()) {
                    Double _val = null;
                    String line_code = "L02";
                    if (tempTableList.size() > 0) {
                        if (baseLineInfoMapper.existLineCodeByHallId(devInfo.getHallId(), "TEMP", "L02") == 0) {
                            _val = dataTempUtilsMapper.getDiffAvgValBylineCode(tempTableList, "L01", "L03", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                            line_code = "L03";
                        } else {
                            _val = dataTempUtilsMapper.getDiffAvgValBylineCode(tempTableList, "L01", "L02", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                            line_code = "L02";
                        }

                    }
                    //挤奶 并且超过20分钟
                    if (_val != null) {
                        if (_val > baseWarnItemMap.get(WarnCodeEnum.W010.getWarnCode()).getMaxVal()) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W010.getWarnCode()) == null) {
                                messageVo.setEndTime(true);
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W010.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, line_code, redisUtil,DeviceWarnEnum.TEMP.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W010.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W010.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W010.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W010.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W010.getWarnCode()));
                                }
                            }
                        }
                    }
                }
                /****
                 * W012 清洗时真空压力低
                 * 清洗时：当有清洗信号时，前1分钟的数值不在记录范围内，清洗信号结束后，计算平均值低于40Kpa。不足1分钟可不报警。
                 * 报警关键因素 L01
                 */
                if (baseWarnItemMap.get(WarnCodeEnum.W012.getWarnCode()) != null && dataMilkVo.getRunTimes() > baseWarnItemMap.get(WarnCodeEnum.W012.getWarnCode()).getIgnoreTimes()) {
                    Double _val = null;
                    if (airpTableList.size() > 0) {
                        _val = dataAirpUtilsMapper.getAvgValByLineCode(airpTableList, "L01", devInfo.getHallId(), dataMilkVo.getRunStartTime(), messageVo.getDataTime());
                    }
                    //挤奶 并且超过20分钟
                    if (_val != null) {
                        if (_val < baseWarnItemMap.get(WarnCodeEnum.W012.getWarnCode()).getMinVal()) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W012.getWarnCode()) == null) {
                                messageVo.setEndTime(true);
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W012.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L01", redisUtil,DeviceWarnEnum.AIRP.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W012.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W012.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W012.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W012.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W012.getWarnCode()));
                                }
                            }
                        }
                    }
                }
                logger.debug("清洗结束valv缓存删除:{}", valvL01Key);
                logger.debug("清洗结束valv缓存删除:{}", valvL02Key);
                logger.debug("清洗结束valv缓存删除:{}", valvFlagKey);
                redisUtil.del(valvL01Key,valvL02Key,valvFlagKey);
                //挤奶中
            } else if (dataMilkVo != null && "L01".equals(dataMilkVo.getLineCode()) && messageVo.getDataVoMap().get("L01") != null && "-1".equals(messageVo.getDataVoMap().get("L01").getVal())) {

                /****
                 * W014 1#制冷机未正常启动
                 * 挤奶信号发出1分钟后，1#制冷机未启动。不足1分钟可不报警
                 * 报警关键因素 L01
                 */
                if (baseWarnItemMap.get(WarnCodeEnum.W014.getWarnCode()) != null && dataMilkVo.getRunTimes() > Constants.NO_1_COOL_MAC_NOT_RUNNING) {
                    String _val = dataMilkUtilsMapper.getStatBylineCode(coolTablePrefix.toString(), "L01", dataMilkVo.getHallId());
                    //挤奶 并且超过20分钟
                    if (_val != null) {
                        if (!"-1".equals(_val)) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W014.getWarnCode()) == null) {
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W014.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L01", redisUtil,DeviceWarnEnum.COOL.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W014.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W014.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W014.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W014.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W014.getWarnCode()));
                                }
                            }
                        }
                    }
                }

                /****
                 * W017 2#制冷机未正常启动
                 * 挤奶信号发出1分钟后，1#制冷机未启动。不足1分钟可不报警
                 * 报警关键因素 L01
                 */
                if (baseWarnItemMap.get(WarnCodeEnum.W017.getWarnCode()) != null && dataMilkVo.getRunTimes() > Constants.NO_2_COOL_MAC_NOT_RUNNING) {
                    String _val = dataMilkUtilsMapper.getStatBylineCode(coolTablePrefix.toString(), "L02", dataMilkVo.getHallId());
                    //挤奶 并且超过20分钟
                    if (_val != null) {
                        if (!"-1".equals(_val)) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W017.getWarnCode()) == null) {
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W017.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L02", redisUtil,DeviceWarnEnum.COOL.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W017.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W017.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W017.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W017.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W017.getWarnCode()));
                                }
                            }
                        }
                    }
                }
            }

            //非挤奶清洗
            if(dataMilkMap != null && dataMilkMap.get("L01") != null && "-0".equals(dataMilkMap.get("L01").getVal())){
                /****
                 * W015 1#制冷机未正常关闭
                 * 挤奶信号结束1分钟后，1#制冷机未停止。不足1分钟可不报警
                 * 报警关键因素 L01
                 */
                if (baseWarnItemMap.get(WarnCodeEnum.W015.getWarnCode()) != null && dataMilkMap.get("L01").getRunTimes() > Constants.NO_1_COOL_MAC_NOT_STOP) {
                    String _val = dataMilkUtilsMapper.getStatBylineCode(coolTablePrefix.toString(), "L01", dataMilkMap.get("L01").getHallId());
                    //挤奶 并且超过20分钟
                    if (_val != null) {
                        if ("-1".equals(_val)) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W015.getWarnCode()) == null) {
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W015.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L01", redisUtil,DeviceWarnEnum.COOL.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W015.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W015.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W015.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W015.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W015.getWarnCode()));
                                }
                            }
                        }
                    }
                }

                /****
                 * W018 2#制冷机未正常关闭
                 * 挤奶信号结束1分钟后，1#制冷机未停止。不足1分钟可不报警
                 * 报警关键因素 L02
                 */
                if (baseWarnItemMap.get(WarnCodeEnum.W018.getWarnCode()) != null && dataMilkMap.get("L01").getRunTimes() > Constants.NO_2_COOL_MAC_NOT_STOP) {
                    String _val = dataMilkUtilsMapper.getStatBylineCode(coolTablePrefix.toString(), "L02", dataMilkMap.get("L01").getHallId());
                    //挤奶 并且超过20分钟
                    if (_val != null) {
                        if ("-1".equals(_val)) {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W018.getWarnCode()) == null) {
                                CommonUtils.insertBaseWarnMsg(session, baseWarnMsgMapper, WarnCodeEnum.W018.getWarnCode(), baseWarnItemMap, messageVo, devInfo, null, "L02", redisUtil,DeviceWarnEnum.COOL.getDeviceCode());
                            } else {
                                baseWarnMsgMapper.initWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W018.getWarnCode()));
                            }
                        } else {
                            if (baseWarnMsgMap.get(WarnCodeEnum.W018.getWarnCode()) != null) {
                                if (baseWarnMsgTimesMap !=null && baseWarnMsgTimesMap.get(WarnCodeEnum.W018.getWarnCode()) > 10) {
                                    CommonUtils.updateBaseWarnMsgEndTimeById(session, baseWarnMsgMapper, baseWarnMsgMap.get(WarnCodeEnum.W018.getWarnCode()), messageVo.getDataTime(), devInfo.getSnNo(), devInfo.getOrgId());
                                } else {
                                    baseWarnMsgMapper.addWarnMsgEndTimes(baseWarnMsgMap.get(WarnCodeEnum.W018.getWarnCode()));
                                }
                            }
                        }
                    }
                }
            }
        }
        Map<String, DataVo> dataVoMap = messageVo.getDataVoMap();

        List<DataMilkVo> returnValList = new ArrayList<DataMilkVo>();
        DataVo dataVo;
        //若为冷热水信息号
        if ("VALV".equals(devInfo.getTypeCode())) {
            if("-1".equals(dataVoMap.get("L01").getVal())){
                logger.debug("valvL01Key:{}", valvL01Key);
                redisUtil.incr(valvL01Key, 1);
            }
            if("-1".equals(dataVoMap.get("L02").getVal())){
                logger.debug("valvL02Key:{}", valvL02Key);
                redisUtil.incr(valvL02Key, 1);
            }
        }
        DataMilkListVo dataMilkListVo;
        //信号同时为 -1 的个数 若挤奶清洗的信号超过1个则需要报警
        for (String key : dataVoMap.keySet()) {
            dataVo = dataVoMap.get(key);
            _dataMilkVo = new DataMilkVo();
            _dataMilkVo.setHallId(devInfo.getHallId());
            _dataMilkVo.setTypeCode(devInfo.getTypeCode());
            _dataMilkVo.setDataTime(messageVo.getDataTime());
            _dataMilkVo.setLineCode(key);
            _dataMilkVo.setVal(dataVo.getVal());

            if ("-1".equals(dataVo.getVal())) {
                //若为清洗或者挤奶 则清除冷热水信息号
                if ("MILK".equals(devInfo.getTypeCode()) && "L01".equals(key)) {
                    //清洗则删除
                    logger.debug("挤奶valv缓存删除:{}", valvL01Key);
                    logger.debug("挤奶valv缓存删除:{}", valvL02Key);
                    logger.debug("挤奶valv缓存删除:{}", valvFlagKey);
                    redisUtil.del(valvL01Key,valvL02Key,valvFlagKey);
                }
                _dataMilkVo.setRunStat("1");
                _dataMilkVo.setRunStatDesc("运行中");
                _dataMilkVo.setRunStatDescEn("Running");
                //添加链表记录
                if (dataMilkListMap.get(key) == null) {
                    dataMilkListVo = new DataMilkListVo();
                    dataMilkListVo.setId(CommonUtils.getUUID());
                    dataMilkListVo.setHallId(devInfo.getHallId());
                    dataMilkListVo.setLineCode(key);
                    dataMilkListVo.setRunStartTime(messageVo.getDataTime());
                    if ("MILK".equals(devInfo.getTypeCode())) {
                        if ("L01".equals(key)) {
                            dataMilkListVo.setRunStatDesc("挤奶时间");
                            dataMilkListVo.setRunStatDescEn("Milking time");
                        } else {
                            dataMilkListVo.setRunStatDesc("清洗时间");
                            dataMilkListVo.setRunStatDescEn("Cleaning time");
                        }
                    }
                    //若当前存在运行设备则需要先关闭
                    if (dataMilkListMap != null && dataMilkListMap.size() > 0) {
                        DataMilkListVo _dataMilkListVo = null;
                        if ("L01".equals(key)) {
                            _dataMilkListVo = dataMilkListMap.get("L02");
                        } else {
                            _dataMilkListVo = dataMilkListMap.get("L01");
                        }

                        CleanDetails cleanDetails = new CleanDetails();
                        //若为清洗结束
                        if ("L02".equals(key) && "MILK".equals(devInfo.getTypeCode())) {
                            String __startDate = _dataMilkListVo.getRunStartTime().substring(0, 8);
                            String __endDate = messageVo.getDataTime().substring(0, 8);
                            List<String> tempTables = this.getTableNames(__startDate, __endDate, devInfo.getOrgId(), "temp");
                            List<String> airpTables = this.getTableNames(__startDate, __endDate, devInfo.getOrgId(), "airp");
                            List<String> tempTabList = utilsMapper.getTableNameListByNames(msgDataDb, tempTables);
                            List<String> airpTabList = utilsMapper.getTableNameListByNames(msgDataDb, airpTables);
                            cleanDetails = dataMilkUtilsMapper.getCleanDetailsByMilkHallId(airpTabList.size() > 0 ? airpTabList : null, tempTabList.size() > 0 ? tempTabList : null, devInfo.getHallId(), _dataMilkListVo.getRunStartTime(), messageVo.getDataTime());
                        }
                        dataMilkListUtilsMapper.updateRunEndTimeById(nowMilkListTableName.toString(), _dataMilkListVo.getId(), messageVo.getDataTime(), cleanDetails.getAvgAirpL01(), cleanDetails.getMaxTempT1(), cleanDetails.getMaxTempT12());
                    }

                    dataMilkListUtilsMapper.insertDataMilkList(nowMilkListTableName.toString(), dataMilkListVo);
                }
            } else {
                _dataMilkVo.setRunStat("0");
                _dataMilkVo.setRunStatDesc("停止中");
                _dataMilkVo.setRunStatDescEn("Stopping");
                if (dataMilkListMap.get(key) != null) {
                    CleanDetails cleanDetails = new CleanDetails();
                    //若为清洗结束
                    if ("L02".equals(key) && "MILK".equals(devInfo.getTypeCode())) {
                        String __startDate = dataMilkMap.get(key).getRunStartTime().substring(0, 8);
                        String __endDate = messageVo.getDataTime().substring(0, 8);
                        List<String> tempTables = this.getTableNames(__startDate, __endDate, devInfo.getOrgId(), "temp");
                        List<String> airpTables = this.getTableNames(__startDate, __endDate, devInfo.getOrgId(), "airp");
                        List<String> tempTabList = utilsMapper.getTableNameListByNames(msgDataDb, tempTables);
                        List<String> airpTabList = utilsMapper.getTableNameListByNames(msgDataDb, airpTables);
                        cleanDetails = dataMilkUtilsMapper.getCleanDetailsByMilkHallId(airpTabList.size() > 0 ? airpTabList : null, tempTabList.size() > 0 ? tempTabList : null, devInfo.getHallId(), dataMilkMap.get(key).getRunStartTime(), messageVo.getDataTime());
                    }
                    dataMilkListUtilsMapper.updateRunEndTimeById(nowMilkListTableName.toString(), dataMilkListMap.get(key).getId(), messageVo.getDataTime(), cleanDetails.getAvgAirpL01(), cleanDetails.getMaxTempT1(), cleanDetails.getMaxTempT12());
                }

            }
            _dataMilkVo.setSnNo(messageVo.getSn());
            _dataMilkVo.setRunStartTime(messageVo.getDataTime());
            _dataMilkVo.setRunTimesStartTime(messageVo.getDataTime());
            _dataMilkVo.setRunTimes(0);
            if (dataMilkMap.get(key) != null && dataMilkMap.get(key) != null && dataMilkMap.get(key).getVal().equals(dataVo.getVal())) {
                _dataMilkVo.setRunStartTime(dataMilkMap.get(key).getRunStartTime());
                long nowDataTime = sdf.parse(messageVo.getDataTime()).getTime();
                long oldDataTime = sdf.parse(dataMilkMap.get(key).getDataTime()).getTime();
                long runTimesStartTime = sdf.parse(dataMilkMap.get(key).getRunTimesStartTime()).getTime();
                int nowOld = (int) ((nowDataTime - oldDataTime) / (1000 * 60));
                if (nowOld < 5) {
                    int munis = (int) ((nowDataTime - runTimesStartTime) / (1000 * 60));
                    _dataMilkVo.setRunTimes(munis);
                    _dataMilkVo.setRunTimesStartTime(dataMilkMap.get(key).getRunTimesStartTime());
                }
            }
            dataMilkUtilsMapper.insertDataMilk(milkStatTableName.toString(), _dataMilkVo);
            returnValList.add(_dataMilkVo);
        }
        try {
            dataMilkUtilsMapper.insertDataMilks(nowMilkTableName, returnValList);
        } catch (Exception e) {
            logger.error("批量插入milk数据报错:{}", e.getMessage());
        }
        //发送消息
        if ("MILK".equals(devInfo.getTypeCode())) {
            logger.debug("挤奶清洗发送app的Json:" + JSON.toJSON(returnValList).toString());
            SessionUtil.sendAppUserMsgByOrgId(session, devInfo.getOrgId(), CommonUtils.toMsg(MsgTypeEnum.H.getTypeCode(), messageVo.getSn(), messageVo.getDataTime(), JSON.toJSON(returnValList).toString()));
        } else {
            logger.debug("辅助设备发送app的Json:" + JSON.toJSON(returnValList).toString());
            SessionUtil.sendAppUserMsgByOrgId(session, devInfo.getOrgId(), CommonUtils.toMsg(MsgTypeEnum.F.getTypeCode(), messageVo.getSn(), messageVo.getDataTime(), JSON.toJSON(returnValList).toString()));
        }
        //发送该牧场的报警总数
        Map<String, Integer> warnCntMap = new HashMap<String, Integer>();
        warnCntMap.put("orgWarnCnt", baseWarnMsgMapper.getWarnMsgCntByMilkOrgId(devInfo.getOrgId()));
        SessionUtil.sendAppUserMsgByOrgId(session, devInfo.getOrgId(), CommonUtils.toMsg(MsgTypeEnum.J.getTypeCode(), messageVo.getSn(), messageVo.getDataTime(), JSON.toJSON(warnCntMap).toString()));
        returnValList.clear();

        return messageVo;
    }

    /***
     * 根据开始时间 结束时间 牧场ID 数据类型
     * @param startDate
     * @param endDate
     * @param orgId
     * @param typ
     * @return
     */
    private List<String> getTableNames(String startDate, String endDate, Integer orgId, String typ) {
        SimpleDateFormat sdf8 = new SimpleDateFormat("yyyyMMdd");
        Calendar _startDate = Calendar.getInstance();
        Calendar _endDate = Calendar.getInstance();
        try {
            _startDate.setTime(sdf8.parse(startDate));
            _endDate.setTime(sdf8.parse(endDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (_startDate.getTimeInMillis() > _endDate.getTimeInMillis()) {
        }

        StringBuffer milkHisTableName = new StringBuffer();
        milkHisTableName.append("data_");
        milkHisTableName.append(typ);
        milkHisTableName.append("_info_");
        milkHisTableName.append(orgId);
        milkHisTableName.append("_");
        List<String> tableNames = new ArrayList<String>();
        while (_startDate.getTimeInMillis() <= _endDate.getTimeInMillis()) {
            tableNames.add(milkHisTableName.toString() + sdf8.format(_startDate.getTime()));
            _startDate.add(Calendar.DATE, 1);
        }
        return tableNames;
    }

}
